package org.jeecg.modules.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.modules.patientImages.entity.PatientImages;
import org.jeecg.common.modules.patientImages.service.IPatientImagesService;
import org.jeecg.common.modules.patientMedicalRecords.entity.PatientMedicalRecords;
import org.jeecg.common.modules.patientMedicalRecords.service.IPatientMedicalRecordsService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.MSWordTool;
import org.jeecg.common.util.WordVO;
import org.jeecg.common.util.ZipUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * @Description: 病历档案表
 * @Author: jeecg-boot
 * @Date:   2021-11-13
 * @Version: V1.0
 */
@Api(tags="病历档案表")
@RestController
@RequestMapping("/patientMedicalRecords/patientMedicalRecords")
@Slf4j
public class PatientMedicalRecordsController extends JeecgController<PatientMedicalRecords, IPatientMedicalRecordsService> {
	@Autowired
	private IPatientMedicalRecordsService patientMedicalRecordsService;
	@Autowired
	private IPatientImagesService patientImagesService;
	/**
	 * 分页列表查询
	 *
	 * @param patientMedicalRecords
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "病历档案表-分页列表查询")
	@ApiOperation(value="病历档案表-分页列表查询", notes="病历档案表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PatientMedicalRecords patientMedicalRecords,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<PatientMedicalRecords> queryWrapper = QueryGenerator.initQueryWrapper(patientMedicalRecords, req.getParameterMap());
		Page<PatientMedicalRecords> page = new Page<PatientMedicalRecords>(pageNo, pageSize);
		IPage<PatientMedicalRecords> pageList = patientMedicalRecordsService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param patientMedicalRecords
	 * @return
	 */
	@AutoLog(value = "病历档案表-添加")
	@ApiOperation(value="病历档案表-添加", notes="病历档案表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PatientMedicalRecords patientMedicalRecords) {
		patientMedicalRecordsService.save(patientMedicalRecords);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param patientMedicalRecords
	 * @return
	 */
	@AutoLog(value = "病历档案表-编辑")
	@ApiOperation(value="病历档案表-编辑", notes="病历档案表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PatientMedicalRecords patientMedicalRecords) {
		patientMedicalRecordsService.updateById(patientMedicalRecords);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "病历档案表-通过id删除")
	@ApiOperation(value="病历档案表-通过id删除", notes="病历档案表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		patientMedicalRecordsService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "病历档案表-批量删除")
	@ApiOperation(value="病历档案表-批量删除", notes="病历档案表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.patientMedicalRecordsService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "病历档案表-通过id查询")
	@ApiOperation(value="病历档案表-通过id查询", notes="病历档案表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PatientMedicalRecords patientMedicalRecords = patientMedicalRecordsService.getById(id);
		if(patientMedicalRecords==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(patientMedicalRecords);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param patientMedicalRecords
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PatientMedicalRecords patientMedicalRecords) {
        return super.exportXls(request, patientMedicalRecords, PatientMedicalRecords.class, "病历档案表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PatientMedicalRecords.class);
    }



	 @RequestMapping(value = "/exportZip", method = RequestMethod.POST)
	 public void exportZip(HttpServletRequest request, HttpServletResponse response, @RequestBody PatientMedicalRecords patientMedicalRecords) {
    	String id = patientMedicalRecords.getId();
		 String fileName = new Date().getTime() + "";
		 WordVO wordVO = new WordVO();
    	//获取病历信息
		  patientMedicalRecords = patientMedicalRecordsService.getById(id);
		//获取图片
		 wordVO.setName(patientMedicalRecords.getPatientName());
		 wordVO.setAge(patientMedicalRecords.getAge()+"");
		 wordVO.setDesction(patientMedicalRecords.getOrtherDesc()+patientMedicalRecords.getDiseaseDesc()+patientMedicalRecords.getMedicineDesc()+patientMedicalRecords.getHosDesc()+patientMedicalRecords.getSystomsDesc());
		 wordVO.setIdCard(patientMedicalRecords.getIdCard());
		 wordVO.setSex(patientMedicalRecords.getSex());
		 wordVO.setIsFirst(patientMedicalRecords.getIsFirst()+"");
		 wordVO.setPhone(patientMedicalRecords.getPhone());
		 wordVO.setTitle(patientMedicalRecords.getPatientName()+"病历");
		 if(patientMedicalRecords.getPatientName() != null){
			 fileName = patientMedicalRecords.getPatientName() +"病历";
		 }
		 //获取病历图片list
		 PatientImages patientImages = patientImagesService.getById(id);
		 List<String> list = new ArrayList<>();
		 //创建文件夹
		 String newfileUrl = MSWordTool.createFile(fileName);
		 List<String> images = new ArrayList<>();
		 wordVO.setOutTilePath(newfileUrl +"//"+fileName+ ".doc");
		 //下载图片到服务器
		 if(patientImages != null){
			 if(patientImages.getImageUrl1()!= null){
				String url = MSWordTool.downImage(patientImages.getImageUrl1(),1,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl2()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl2(),2,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl3()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl3(),3,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl4()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl4(),4,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl5()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl5(),5,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl6()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl6(),6,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl7()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl7(),7,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl8()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl8(),8,newfileUrl);
				 list.add(url);
			 }
			 if(patientImages.getImageUrl9()!= null){
				 String url = MSWordTool.downImage(patientImages.getImageUrl9(),9,newfileUrl);
				 list.add(url);
			 }
		 }
		 wordVO.setImages(list);
		 //从服务器下载图片，并形成word
		 MSWordTool.outTilePath(wordVO);
		 //文件压缩为zip
		 String zipUrl = MSWordTool.fileUrl + "/" + fileName+".zip";
		 ZipUtils.createZip(newfileUrl, zipUrl);
		 URL urlfile = null;
		 HttpURLConnection httpUrl = null;
		 BufferedInputStream bis = null;
		 BufferedOutputStream bos = null;

//		 try {
//			 response.setHeader("Content-Disposition", "inline;filename=" +new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
//			 urlfile = new URL("https://dayizhihui.oss-cn-beijing.aliyuncs.com/common/1.zip");
//			 httpUrl = (HttpURLConnection) urlfile.openConnection();
//			 httpUrl.connect();
//			 bis = new BufferedInputStream(httpUrl.getInputStream());
//			 bos = new BufferedOutputStream(response.getOutputStream());
//			 int len = 2048;
//			 byte[] b = new byte[len];
//			 while ((len = bis.read(b)) != -1) {
//				 bos.write(b, 0, len);
//			 }
//			 bos.flush();
//			 bis.close();
//			 httpUrl.disconnect();
//		 } catch (Exception e) {
//			 e.printStackTrace();
//		 } finally {
//			 try {
//				 bis.close();
//				 bos.close();
//			 } catch (IOException e) {
//				 e.printStackTrace();
//			 }
//		 }
		 try {
			 File file = new File(zipUrl);
			 response.setCharacterEncoding("UTF-8");
			 response.setHeader("Content-Disposition",
					 "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
			 response.setContentLength((int) file.length());
			 response.setContentType("application/zip");// 定义输出类型
			 FileInputStream fis = new FileInputStream(file);
			 BufferedInputStream buff = new BufferedInputStream(fis);
			 byte[] b = new byte[1024];// 相当于我们的缓存
			 long k = 0;// 该值用于计算当前实际下载了多少字节
			 OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
			 // 开始循环下载
			 while (k < file.length()) {
				 int j = buff.read(b, 0, 1024);
				 k += j;
				 myout.write(b, 0, j);
			 }
			 myout.flush();
			 buff.close();
		 file.delete();
		 } catch (Exception e) {
			 System.out.println(e);
		 }
	 }

}
